package yxy.game.pm2.command.resonate;

import org.apache.commons.lang3.StringUtils;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.resonancedata;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.Format;
import yxy.game.pm2.bean.Hero;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.currency.CurrencyNotEnoughException;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ResonateMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.battle.BattleHandle;
import yxy.game.pm2.module.hero.FormatHandle;
import yxy.game.pm2.module.resonate.ResonateHandle;
import yxy.game.pm2.module.resonate.ResonateHeroMsg;
import yxy.game.pm2.module.resonate.ResonateModule;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author ljb
 * @name CMD_ResonateConfirm
 * @descrition 共鸣系统共鸣确认
 * @since 2022-07-27
 */
@MessageType(proto = Command.ResonateConfirm, classtype = ResonateMessage.ResonateConfirmRequest.class)
public class CMD_ResonateConfirm extends Command<ResonateMessage.ResonateConfirmRequest> {

    @Override
    public void execute(MessageSource messageSource, ResonateMessage.ResonateConfirmRequest request) {
        String playerCode = messageSource.getTag();
        String resonateHeroId = request.getResonateHeroId();
        int field = request.getResonatePosition();
        ResonateMessage.ResonateConfirmResponse.Builder response = ResonateMessage.ResonateConfirmResponse.newBuilder();

        try {
            ResonateModule module = ResonateModule.get(playerCode);

            if (module == null) {
                send(messageSource, response, Result.DataError);
                return;
            }

            //resonancedata表
            resonancedata data = DataCenter.getData(field, resonancedata.class);

            Result result = null;
            //todo 如果不传resonateHeroId只是开启格子
            if (StringUtils.isEmpty(resonateHeroId)) {
                result = openField(field, playerCode, data, module);
            }

            //todo 开格子且共鸣武将
            if (!StringUtils.isEmpty(resonateHeroId)) {
                result = openFieldWithHero(field, data, playerCode, resonateHeroId, module);
            }

            //返回
            response.addAllAboveHeros(ResonateHandle.getAboveHeroList(module));//场上的武将信息
            response.addAllResonateHeros(ResonateHandle.getResonateHeros(module));//共鸣的武将信息


            send(messageSource, response, result);
        } catch (Exception e) {
            e.printStackTrace();
            send(messageSource, response, Result.DataError);

        }
    }

    private Result openFieldWithHero(int field, resonancedata data, String playerCode, String resonateHeroId, ResonateModule module) {
        PlayerBean playerBean = PlayerBean.get(playerCode);
        if (field <= 0 || data == null) {
            return Result.DataError;
        }

        if (playerBean.getLevel() < data.getNeedlevel()) {
            return Result.ResonateConfirmNeedlevel;//主公等级不满足
        }

        Hero hero = Hero.get(playerCode, resonateHeroId);
        if (hero == null) {
            return Result.DataError;
        }

        //todo 2.获取已共鸣的武将信息,共鸣武将的code不能重复
        ArrayList<String> codes = new ArrayList<>();
        ArrayList<ResonateHeroMsg> resonateHeros = module.getResonateHeros();
        for (ResonateHeroMsg msg : resonateHeros) {
            if (msg == null || StringUtils.isEmpty(msg.getCode())) continue;
            codes.add(msg.getCode());
        }

        if (codes.contains(resonateHeroId)) {
            return Result.ResonateConfirmCantResonateHero;
        }

        //todo 3.场上的武将不满足6个则不能共鸣
        HashMap<String, ResonateHeroMsg> aboveHeros = module.getAboveHeros();
        if (aboveHeros.size() < 6) {
            return Result.ResonateConfirmAbsenceAboveHero;
        }

        //todo 4.共鸣武将的code不能是场上的武将
        ArrayList<String> aboveHeroList = new ArrayList<>();//阵上的武将

        for (ResonateHeroMsg value : aboveHeros.values()) {
            aboveHeroList.add(value.getCode());
        }

        if (aboveHeroList.contains(resonateHeroId)) {
            return Result.ResonateConfirmCantRepeat;
        }


        //todo 5.消耗（材料不满足可以用元宝）
        Boolean isGone = true;
        //优先材料  后元宝  都不满足返回信息
        if (Currency.number(playerCode, CurrencyType.forNumber(data.getRewardtype()), data.getRewardid(), false) >= data.getRewardnum()) {
            //消耗
            Currency cost = Currency.create(data.getRewardtype(), data.getRewardid(), data.getRewardnum());
            try {
                new CurrencyHandle().cost(playerCode, CCReason.共鸣系统, cost);
            } catch (CurrencyNotEnoughException e) {

                return new Result(Result.CostFail, e.getType().getNumber(), e.getDataId());//消费不足
            }
            isGone = false;
        }

        //元宝消耗
        if (isGone) {
            //消耗
            Currency cost = Currency.create(data.getRewardtype2(), data.getRewardid2(), data.getRewardnum2());
            try {
                new CurrencyHandle().cost(playerCode, CCReason.共鸣系统, cost);
            } catch (CurrencyNotEnoughException e) {
                return new Result(Result.CostFail, e.getType().getNumber(), e.getDataId());// 消费不足
            }
        }

        //todo 6.武将共鸣逻辑
        ResonateHeroMsg heroMsg = ResonateHandle.ResonateLogic(hero, module, playerCode);
        module.getResonateHeros().add(heroMsg);
        module.set();


        //todo 6.更新战力
        BattleHandle battleHandle = new BattleHandle();

        //判断是不是在队伍，更新战力
        FormatHandle formatHandle = new FormatHandle();
        ArrayList<String> list = formatHandle.formatCodesList(playerCode, Format.get(playerCode, Format.FormatType.普通));

        if (list.contains(resonateHeroId)) {
            battleHandle.power(playerCode, hero);
        }

        return Result.Success;
    }

    private Result openField(int field, String playerCode, resonancedata data, ResonateModule module) {

        PlayerBean playerBean = PlayerBean.get(playerCode);
        if (field <= 0 || data == null) {
            return Result.DataError;
        }

        if (playerBean.getLevel() < data.getNeedlevel()) {
            return Result.ResonateConfirmNeedlevel;//主公等级不满足
        }

        //todo 消耗（材料不满足可以用元宝）
        Boolean isGone = true;
        //优先材料  后元宝  都不满足返回信息
        if (Currency.number(playerCode, CurrencyType.forNumber(data.getRewardtype()), data.getRewardid(), false) >= data.getRewardnum()) {
            //消耗
            Currency cost = Currency.create(data.getRewardtype(), data.getRewardid(), data.getRewardnum());
            try {
                new CurrencyHandle().cost(playerCode, CCReason.共鸣系统, cost);
            } catch (CurrencyNotEnoughException e) {

                return new Result(Result.CostFail, e.getType().getNumber(), e.getDataId());//消费不足
            }
            isGone = false;
        }

        //元宝消耗
        if (isGone) {
            //消耗
            Currency cost = Currency.create(data.getRewardtype2(), data.getRewardid2(), data.getRewardnum2() * data.getRewardnum());
            try {
                new CurrencyHandle().cost(playerCode, CCReason.共鸣系统, cost);
            } catch (CurrencyNotEnoughException e) {
                return new Result(Result.CostFail, e.getType().getNumber(), e.getDataId());// 消费不足
            }
        }

        //开格子
        ArrayList<ResonateHeroMsg> resonateHeros = module.getResonateHeros();
        resonateHeros.add(new ResonateHeroMsg());
        module.set();
        return Result.Success;
    }

    private void send(MessageSource messageSource, ResonateMessage.ResonateConfirmResponse.Builder response, Result result) {
        response.setResult(result.packResult());
        MessageEmitterHandler.getInstance().send(messageSource, response.build());
    }
}